<?php
/**
 * @author Martin Pernica
 * @copyright 2009
 */

Text::h2( Lang::getBack('com_user', 'fields_new') );
echo '<br /><h3><a href="index.php?p=components&name=user&a=fields">'.Lang::getBackGlobal('back').'</a></h3><br />';

$cats = $db->query("SELECT id,title FROM {prefix}fields_cats ORDER BY id");

while ($d = $cats->fetch_assoc()) {
    $cats_final[$d['title']] = $d['id'];
}

$form = new Form("", "post");

$form->addElement("input", array("type" => "text", "name" => "desc", "value" =>
    $_POST['desc'], "label" => Lang::getBack('com_user', 'fields_desc')));

$form->addElement("input", array("type" => "text", "name" => "sql_name", "value" =>
    $_POST['sql_name'], "label" => Lang::getBack('com_user', 'fields_unique')));

$form->addElement("select", array("name" => "category", "label" => Lang::getBack('com_user', 'fields_category'),
    "selected" => $_POST['category']), $cats_final);

$form->addElement("input", array("type" => "submit", "name" => "submit", "value" =>
    Lang::getBackGlobal('submit')));

$form->render();

if ($form->isSubmitted()) {

    $sql_name = $db->real_escape_string($_POST['sql_name']);
    $category = intval($_POST['category']);
    $desc = $db->real_escape_string($_POST['desc']);

    $test = $db->query("SELECT id FROM {prefix}fields WHERE sql_name = '" . $sql_name .
        "'");

    if ($test->num_rows == 0 and preg_match('/^[a-z0-9]*$/i', $sql_name)) {
        
        $query = $db->query("INSERT INTO {prefix}fields(`catid`, `desc`, `sql_name`) VALUES( '" .
            $category . "', '" . $desc . "', 'field_" . $sql_name . "')");
        $query = $db->query("ALTER TABLE {prefix}fields_data ADD COLUMN field_" . $sql_name .
            " text");
        
        if ($query) {
            $log->write(8, 'com_user', 'NOW()', 'User added field ' . $desc, $_SESSION['id']);
            messageBox( Lang::getBack('com_user', 'fields_true') );
        }
        
    } else {
        echo '<p class="msg error">'.Lang::getBack('com_user', 'fields_false').'</p>';
    }
}

?>